import { boolToYN, convertFileToBase64 } from "@/utils";
import { VehicleData, DocumentItem } from "./types";
enum VehicleType {
  privateCar = "PRIVATE_CAR",
  LGV = "LGV",
  motorcycle = "MOTOR_CYCLE",
}
const convertVehicleType = (type: string): string => {
  return VehicleType[type as keyof typeof VehicleType] || type;
};
export const processVehicleData = (
  data: VehicleData
): {
  lpnNo: string;
  octopus: string;
  lpnNoInput: string;
  vehType: string;
  authLetter: boolean | string;
  dppp: boolean | string;
  authFile: DocumentItem[];
  dpppFile: DocumentItem[];
  vehicle: DocumentItem[];
} => {
  const {
    lpnNo,
    octopus,
    lpnNoInput,
    vehType,
    dpppFile,
    vehicle,
    authFile,
    authLetter,
    dppp,
  } = data;

  return {
    lpnNo,
    octopus,
    lpnNoInput,
    vehType,
    authFile,
    authLetter,
    dppp,
    dpppFile,
    vehicle,
  };
};

// 合并多个车辆数据
export const consolidateData = async (
  dataArray: VehicleData[]
): Promise<any> => {
  const lpnData = dataArray.map((data) => {
    const processedData = processVehicleData(data);

    // 提取文档数据
    const { authFile, dpppFile, vehicle } = processedData;
    console.log(dpppFile, "dpppFile");
    const doc = [
      ...(Array.isArray(authFile)
        ? authFile.map((item) => ({
            fileName: item.name,
            lpnDocType: "AUTH_LETER",
            data: item.originFileObj,
          }))
        : []),
      ...(Array.isArray(dpppFile)
        ? dpppFile.map((item) => ({
            fileName: item.name,
            lpnDocType: "DPPP",
            data: item.originFileObj,
          }))
        : []),
      ...(Array.isArray(vehicle)
        ? vehicle.map((item) => ({
            fileName: item.name,
            lpnDocType: "LPN",
            data: item.originFileObj,
          }))
        : []),
    ];

    return {
      lpnNo: processedData.lpnNo,
      vehType: convertVehicleType(processedData.vehType),
      lpnNoInput: processedData.lpnNoInput,
      dppp: boolToYN(processedData.dppp),
      authLetter: boolToYN(processedData.authLetter),
      octopus: processedData.octopus,
      doc, // 嵌入文档数据
    };
  });
  for (const lpnIndex in lpnData) {
    if (Object.prototype.hasOwnProperty.call(lpnData, lpnIndex)) {
      // 使用 call 方法
      const { doc } = lpnData[lpnIndex];
      for (const i in doc) {
        if (Object.prototype.hasOwnProperty.call(doc, i)) {
          // 使用 call 方法
          const { data } = doc[i];
          const bynaryData = await convertFileToBase64(data);
          //@ts-ignore
          lpnData[lpnIndex].doc[i].data = bynaryData;
          // const filedUint8Array = await doc[i].data();
        }
      }
    }
  }
  return {
    lpnData, // 返回包含多个对象的数组
  };
};
